<template>
	<view class="wrap">
		<view class="subwrap">
			<uv-form ref="uvForm" :model="item" :rules="rules" :borderBottom="false" labelWidth="auto" labelPosition="top" :labelStyle="labelStyle" errorType="toast">
				<uv-form-item label="帖子标题" prop="title">
					<uv-input v-model="item.title" border="surround" :maxlength="100" :customStyle="customStyle01" :trim="true" placeholder="请输入" />
				</uv-form-item>
				
				<uv-form-item label="帖子分类" prop="cate">
					<uv-subsection :list="$mData.postCates02" :current="item.cate - 1" mode="button" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="cateSubsectionChange"></uv-subsection>
				</uv-form-item>
				
				<uv-form-item label="帖子正文" prop="content">
					<uv-textarea type="textarea" v-model="item.content" :height="100" autoHeight :maxlength="99999" count :customStyle="customStyle01" placeholder="请输入" />
				</uv-form-item>
				
				<uv-form-item label="上传视频（可选项）" prop="video">
					<uv-upload :fileList="fileListVideo" name="Video" accept="video" :maxCount="1" :maxSize="100 * 1024 * 1024" @afterRead="afterRead" @delete="trash"></uv-upload>
				</uv-form-item>
				
				<uv-form-item label="上传图片（可选项）" prop="images">
					<uv-upload :fileList="fileListImage" name="Image" accept="image" previewFullImage previewImage multiple :maxCount="9" :maxSize="5 * 1024 * 1024" @afterRead="afterRead" @delete="trash"></uv-upload>
				</uv-form-item>
				
				<uv-button type="warning" form-type="submit" @click="submit" :loading="submitLoading" shape="circle" :ripple="true" :customStyle="customStyle02">提交</uv-button>
			</uv-form>
		</view>
	</view>
</template>

<script>
import { postMyView, postForm, fileImages, fileVideos } from '@/api/core';

export default {
	data() {
		return {
			$mData: this.$mData,
			errorType: ['toast', 'message', 'borderBottom'],
			submitLoading: false,
			fileListVideo: [],
			fileListImage: [],
			id: 0,
			item: {
				title: '',
				cate: 1,
				content: '',
				images: [],
				video: ''
			},
			rules: {
				title: this.$mData.rules.title,
				content: this.$mData.rules.content_forum,
				//images: this.$mData.rules.images,
			},
		};
	},
	onLoad(option) {
		this.id = option.id ? option.id : this.id;
	},
	onShow() {
		this.initLogin();
	},
	onReady(res) {
		if (this.id) {
			uni.setNavigationBarTitle({
			  title: '编辑帖子'
			});
		}
		
		this.$refs.uvForm.setRules(this.rules);
	},
	mounted() {
		this.initData();
	},
	computed: {
		labelStyle() {
			return {
				height: '30rpx',
				fontSize: '30rpx',
				borderLeft: `6rpx ${this.themeColor.color} solid`,
				borderRadius: '3rpx',
				paddingLeft: '20rpx',
				margin: '0 0 20rpx 0'
			}
		},
		customStyle01() {
			return {
				borderRadius: '16rpx',
				padding: '20rpx 30rpx',
				marginTop: '20rpx'
			}
		},
		customStyle02() {
			return {
				background: this.themeColor.color,
				color: '#FFF',
				fontSize: '30rpx',
				borderColor: this.themeColor.color,
				padding: '46rpx 0',
				marginTop: '60rpx'
			}
		}
	},
	methods: {
		async initLogin() {
			let hasLogin = this.$mStore.getters.hasLogin;
			
			if (!hasLogin) {
				this.navTo('/pages/public/logintype');
			}
		},
		async initData() {
			if (this.id) {
				await this.getView();
			}
		},
		navTo(route) {
			this.$mRouter.push({ route });
		},
		async getView() {
			await this.$http.get(`${postMyView}`, {
				id: this.id
			}).then(async r => {
				this.loading = false;
				this.item = r.data;
				this.item.datetime_name = this.$uv.timeFormat(this.item.datetime, 'yyyy-mm-dd hh:MM');
				
				let images = [];

				this.item.images.forEach((image, index) => {
					images.push({ url: image });
				});
				
				this.fileListImage = images;
				this.fileListVideo[0] = this.item.video;
			}).catch(err => {
				this.loading = false;
			});
		},
		submit() {
			let images = [];
			let videos = [];

			this.fileListImage.forEach((item, index) => {
				images.push(item.url);
			});
			
			this.fileListVideo.forEach((item, index) => {
				this.item.video = item.url;
			});
			
			this.item.images = images;
		
			this.$refs.uvForm.validate().then(res => {
				if (res) {
					this.postItem(this.item);
				}
			});
		},
		postItem(params) {
			this.submitLoading = true;
			let url = `${postForm}`;
			if (this.id) url += `?id=${this.id}`;
			
			this.$http.post(url, {
				...params,
			}).then(async r => {
				this.submitLoading = false;
				
				let _this = this;

				uni.showModal({
					content: '发布成功！可能需审核通过后显示。',
					showCancel: false,
					success(res) {
						if (res.confirm) {
							_this.$mRouter.back();
						}
					}
				});
			}).catch(err => {
				this.submitLoading = false;
			});
		},
		cateSubsectionChange(index) {
			this.item.cate = index + 1;
		},
		async afterRead(event) {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			let uploadUrl = this.$mConfig.baseUrl;
			
			switch (event.name){
				case 'Image':
					uploadUrl += fileImages;
					break;
				case 'Video':
					uploadUrl += fileVideos;
					break;
				default:
					break;
			}
			
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			// 此写法可以避免使用老写法在VUE3中不更新
			// #ifdef VUE3
			this[`fileList${event.name}`] = this[`fileList${event.name}`].filter((item, index) => {
			  return index>=0
			});
			// #endif

			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url, uploadUrl);
				let item = this[`fileList${event.name}`][fileListLen];
				let res = JSON.parse(result);
				
				this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: res.data.url
				}));
				
				fileListLen++;
			}
		},
		uploadFilePromise(url, uploadUrl) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: uploadUrl,
					filePath: url,
					name: 'file',
					formData: {},
					success: (res) => {
						setTimeout(() => {
							resolve(res.data);
						}, 1000);
					}
				});
			});
		},
		trash(event) {
			this[`fileList${event.name}`] = this[`fileList${event.name}`].filter((item,index) => {
			  return index != event.index
			})
		},
	}
};
</script>

<style lang="scss">
page {
	background: $color-white;
	
	.wrap {
		padding: 30rpx;
		
		.subwrap {
			background: $color-white;
			
			.progress-tips {
				color: $uv-warning;
				font-size: 24rpx;
				padding: 10rpx;
			}
		}
	}
}
</style>
